﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.UI;
using UTSDAL.LINQSQL.Model;
using UTSDAL.LINQSQL.DAO;


namespace UTS.Controls
{
    [
        DefaultProperty("Text"),
        ToolboxData("<{0}:CohortDropDownList runat=\"server\"> </{0}:CohortDropDownList>")
    ]
    public class CohortDropDownList : System.Web.UI.WebControls.DropDownList
    {

        private CohortDAO cohortDAO = new CohortDAO();

        private void init()
        {

            this.DataSource = cohortDAO.selectAll();
            this.DataBind();
            DropDownUtils.addDefaultLabel(this, "Select a Cohort");
            this.DataTextField = "CohortName";
            this.DataValueField = "CohortId";
        }

        // this method bypasses non post back requests by ajax
        public void reload()
        {
            init();
        }

        

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                base.OnLoad(e);

                init();
            }
        }


        private Cohort cohort = null;

        public Cohort Cohort
        {
            get 
            {
                if (StringUtils.isValidGuid(this.SelectedValue.ToString()))
                {
                    cohort = cohortDAO.findById(new Guid(this.SelectedValue.ToString()));
                }
                else
                {
                    cohort = null;
                }
                return cohort; 
            }
            set 
            { 
                cohort = value;
                if (this.cohort != null)
                {
                    this.SelectedValue = cohort.CohortId.ToString();
                }
            }
        }


    }
}